package com.controller;

import com.servcice.StudentService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.InternalResourceView;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/****
 * 用户登录Controller
 *
 * @author Swinglife
 *
 */
@Controller
public class LoginController {
	// 处理用户业务类
	@Autowired
	private StudentService studentService;
	@Autowired
	public EnterpriseCacheSessionDAO sessionDao;

	public StudentService getStudentService() {
		return studentService;
	}

	public void setStudentService(StudentService studentService) {
		this.studentService = studentService;
	}

	public EnterpriseCacheSessionDAO getSessionDao() {
		return sessionDao;
	}

	public void setSessionDao(EnterpriseCacheSessionDAO sessionDao) {
		this.sessionDao = sessionDao;
	}

	/***
	 * 跳转到登录页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/toLogin")
	public ModelAndView toLogin() {
		// 跳转到/page/login.jsp页面
		return new ModelAndView("/accountlogin");
	}

	/***
	 * 实现用户登录
	 *
	 * @param username
	 * @param password
	 * @return
	 */

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView Login(String username, String password, String rememberMe, HttpServletRequest request) {
		System.out.println(username + "--------------------1111 " + password + " " + rememberMe);
		Subject subject = SecurityUtils.getSubject();//利用shiro的安全管理工具得到登录对象

		UsernamePasswordToken token = new UsernamePasswordToken(username, password);// 令牌，有多种，账号密码组合作为令牌，设备编号作为令牌

		//禁止已登录用户
//		Collection<Session> sessions = sessionDao.getActiveSessions();
//        for (Session session : sessions) {
//
//            System.out.println("登录用户" + session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY));
//            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) != null) {
//                return  new ModelAndView("accountlogin", "msg", "该用户已登录");
//            }
//        }


//判断用户是否勾选记住我，勾选记住我，读取cookie登录
		boolean remembermeRusult = rememberMe == null ? false : true; // null=>false
		if (remembermeRusult) {
			token.setRememberMe(remembermeRusult);
		}
		String error = null;
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			error = "用户名错误";
		} catch (IncorrectCredentialsException e) {
			error = "用户名/密码错误";
		} catch (ExcessiveAttemptsException e) {
			// TODO: handle exception
			error = "登录失败多次，账户锁定10分钟";
		} catch (AuthenticationException e) {
			// 其他错误，比如锁定，如果想单独处理请单独catch处理
			e.printStackTrace();
			error = "其他错误：" + e.getMessage();
		}
		ModelAndView mv = new ModelAndView();
		if (error != null) {// 出错了，返回登录页面
			mv = new ModelAndView("/accountlogin","msg", error);
		} else {// 登录成功
            String modelname = request.getParameter("loginOption");
            if(Optional.ofNullable(modelname).isPresent()) {
				mv  = new ModelAndView("/front/"+modelname+"/home");
			}else{
				mv = new ModelAndView("/accountlogin","msg", "非法操作，请重新登录");
			}
		}

		return mv;
	}

}